package com.bjpowernode.micrpaykq.controller;

import com.bjpowernode.api.model.RechargeRecord;
import com.bjpowernode.api.model.SysUser;
import com.bjpowernode.api.service.RechargeService;
import com.bjpowernode.api.service.UserService;
import com.bjpowernode.contacts.RedisKey;
import com.bjpowernode.contacts.YLBConst;
import com.bjpowernode.micrpaykq.service.KQService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * ClassName:KuaiQianController
 * Date:2022/1/4 11:16
 */
@Controller
public class KQController {

    @Autowired
    private KQService kqService;

    @DubboReference(interfaceClass = UserService.class,version = "1.0")
    private UserService userService;

    @DubboReference(interfaceClass = RechargeService.class,version = "1.0")
    private RechargeService rechargeService;

    //注入redis模板类
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*接收vue项目的请求， 接收充值的的请求， 在代码中调用快钱的支付接口*/
    @GetMapping("/receive/kq/recharge")
    public String receVueRequest(@RequestParam Integer userId,
                                 @RequestParam BigDecimal money,
                                 @RequestParam String token, Model model) {
        //参数的判断处理
        String viewName = "err";
        try{
            if (userId > 0 && money.doubleValue() > 0) {
                SysUser user = userService.queryByUserId(userId);
                if( user != null ){
                    //生成表单数据
                    Map<String, String> params = kqService.generateFormData(
                            userId, money, user.getPhone(),token);

                    //如果生成表单数据没有问题， 增加一个充值记录
                    RechargeRecord record = new RechargeRecord();
                    record.setChannel("kq");
                    record.setRechargeDesc("购买理财");
                    record.setRechargeMoney(money);
                    record.setRechargeNo(params.get("orderId"));
                    record.setRechargeStatus(YLBConst.RECHARGE_PROCESSING);
                    record.setRechargeTime(new Date());
                    record.setUid(userId);
                    rechargeService.addRecharge(record);

                    //把订单号存放到redis， 当收到异步通知后，删除这个订单号，剩下的就是要处理的调单的订单号
                    //ZSet, value=订单号， score = 充值时间
                    boolean add = stringRedisTemplate.opsForZSet().add(
                            RedisKey.RECHARGE_ORDERID_LIST,
                            params.get("orderId"),
                            record.getRechargeTime().getTime());

                    model.addAllAttributes(params);
                }
                //返回值是视图
                viewName = "kqForm";
            }
        }catch (Exception e){
            e.printStackTrace();
            viewName = "err";
        }
        return viewName;
    }


    /*接收快钱发送支付结果（异步通知）*/
    /*
     * 处理异步通知：
     * 1.接收所有的参数，进行验签
     * 2.验证签名通过过，处理业务逻辑
     * 3.检查订单是否是商家自己的，比较merchantAcctId
     * 4.检查订单是否在商家有， 同时判断订单的状态（0的状态可以处理)
     * 5.判断快钱通知的付款金额和商家资金的订单金额是否一致
     * 6.给用户的资金账号增加金额
     * 7.修改充值记录的状态（1或2）。
     * 8.删除redis中存在的订单
     *
     * */
    @GetMapping("/receive/kq/notify")
    @ResponseBody
    public String receiveKqNotify(HttpServletRequest request) {
     /*   StringBuilder builder = new StringBuilder("");
        Enumeration<String> names = request.getParameterNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            String value = request.getParameter(name);
            builder.append(name).append("=").append(value).append("&");

        }
        System.out.println("接收的快钱提供给商家的支付结果参数："+builder.toString());*/

       //处理异步通知
        kqService.doKqNotify(request);
        //删除redis订单号
        stringRedisTemplate.opsForZSet().remove(
                RedisKey.RECHARGE_ORDERID_LIST,request.getParameter("orderId"));

        return "<result>1</result><redirecturl>http://123.249.17.208:70 00/user/recharge/showResult</redirecturl>";
    }


    //入口， 在定时任务程序中，通过HttpClient调用此接口
    @GetMapping("/receive/task/kq/query")
    @ResponseBody
    public String receMicrTask(){
        System.out.println("执行了快钱订单查询功能");
        //1从redis获取要处理的订单
        Set<String> orderIds = stringRedisTemplate.opsForZSet()
                         .range(RedisKey.RECHARGE_ORDERID_LIST, 0, -1);
        kqService.doKqQueryOrder(orderIds);
        return "开始查询";
    }
}
